package org.zjt.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/4/13.
 */
public class ZKConnectCenter {

    private CuratorFramework  cf ;
    private static final int SESSION_OUTTIME = 5000;

    public  ZKConnectCenter(RegisterConfig registerConfig)throws Exception{
        List<String>  v1= registerConfig.getZkConfigs().stream()
                .map(a -> String.format("%s:%S",a.getHost(),a.getPort()))
                .collect(Collectors.toList());
        String connect = String.join(",",v1);
        if ( connect == null )
            throw new NullPointerException("zkconfig is empty");
        //1 重试策略：初试时间为1s 重试10次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        //2 通过工厂创建连接
         cf = CuratorFrameworkFactory.builder()
                .connectString(connect)
                .sessionTimeoutMs(SESSION_OUTTIME)
                .retryPolicy(retryPolicy)
                .build();
        //3 建立连接
        cf.start();
    }


    public CuratorFramework getZKConnect() {
        return cf;
    }

}
